﻿using System;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Info;
using System.Xml.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace MaciejGrabek.WP7.Services.Phone.Tools
{
    public static class IdsProvider
    {
        private const int IdentifierLength = 32;
        private const int IdentifierOffset = 2; 

        public static string GetUserId()
        {
            object anid;
            if (UserExtendedProperties.TryGetValue("ANID", out anid))
            {
                if (anid != null && anid.ToString().Length >= (IdentifierLength + IdentifierOffset))
                {
                    return anid.ToString().Substring(IdentifierOffset, IdentifierLength);
                }
            }

            return null;
        }


        public static string GetDeviceId()
        {
            object uniqueId;
            if (DeviceExtendedProperties.TryGetValue("DeviceUniqueId", out uniqueId))
            {
                byte[] temp = (byte[])uniqueId;
                return Encoding.UTF8.GetString(temp, 0, temp.Length);
            }

            return String.Empty;
        }

        public static string ApplicationId
        {
            get
            {
                using (var strm = TitleContainer.OpenStream("WMAppManifest.xml"))
                {
                    XElement xml = XElement.Load(strm);
                    string prodId = "";

                    try
                    {
                        prodId = (from app in xml.Descendants("App")
                                  select app.Attribute("ProductID").Value).FirstOrDefault();
                    }
                    catch (Exception ex)
                    {
                        return "";
                    }

                    return prodId.Replace("{", "").Replace("}", "");
                }
            }
        }
    }
}